package cl.jpavlich.mpm.view;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;

import javax.swing.JComponent;
import javax.swing.JOptionPane;

import org.metawidget.swing.SwingMetawidget;
import org.metawidget.swing.widgetbuilder.OverriddenWidgetBuilder;
import org.metawidget.swing.widgetbuilder.ReadOnlyWidgetBuilder;
import org.metawidget.swing.widgetbuilder.SwingWidgetBuilder;
import org.metawidget.swing.widgetprocessor.binding.beansbinding.BeansBindingProcessor;
import org.metawidget.widgetbuilder.composite.CompositeWidgetBuilder;
import org.metawidget.widgetbuilder.composite.CompositeWidgetBuilderConfig;

import cl.jpavlich.mpm.services.Bundle;
import cl.jpavlich.mpm.view.metawidgets.URLWidgetBuilder;

public class GUIUtils {

	@SuppressWarnings("unchecked")
	public static SwingMetawidget createMetaWidget(boolean readOnly) {
		SwingMetawidget mw = new SwingMetawidget();
		mw.setConfig("cl/jpavlich/mpm/view/config/metawidget.xml");
		mw.setBundle(Bundle.getInstance());
		mw.setReadOnly(readOnly);

		mw.setWidgetBuilder(new CompositeWidgetBuilder<JComponent, SwingMetawidget>(
				new CompositeWidgetBuilderConfig<JComponent, SwingMetawidget>()
					.setWidgetBuilders(
							new OverriddenWidgetBuilder(),
							new ReadOnlyWidgetBuilder(),
							new SwingWidgetBuilder(),
							new URLWidgetBuilder()
		)));

		return mw;
		// SwingMetawidget metawidget = new SwingMetawidget();
		// metawidget.setInspector(new CompositeInspector(
		// new CompositeInspectorConfig().setInspectors(
		// new PropertyTypeInspector(),
		// new MetawidgetAnnotationInspector(),
		// new Java5Inspector(),
		// new JexlInspector()
		// )));
		// metawidget
		// .setWidgetBuilder(new CompositeWidgetBuilder<JComponent,
		// SwingMetawidget>(
		// new CompositeWidgetBuilderConfig<JComponent, SwingMetawidget>()
		// .setWidgetBuilders(
		// new CollectionWidgetBuilder(),
		// new SwingWidgetBuilder())));
		// metawidget.addWidgetProcessor(new BeansBindingProcessor(new
		// BeansBindingProcessorConfig()
		// .setUpdateStrategy( UpdateStrategy.READ_WRITE )));
		//
		// return metawidget;
	}

	public static SwingMetawidget createMetaWidget(Object obj, boolean readOnly) {
		SwingMetawidget metawidget = createMetaWidget(readOnly);
		metawidget.setToInspect(obj);
		return metawidget;
	}

	public static void save(SwingMetawidget mw) {
		mw.getWidgetProcessor(BeansBindingProcessor.class).save(mw);
		mw.setToInspect(mw.getToInspect());

	}

	public static void center(Window w) {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		w.setLocation((int) ((screenSize.getWidth() - w.getWidth()) / 2),
				(int) ((screenSize.getHeight() - w.getHeight()) / 2));
	}
	
	public static void showErrorDialog(Throwable t) {
		JOptionPane.showMessageDialog(null, t.getMessage(), "Error",
				JOptionPane.ERROR_MESSAGE);
	}
}
